using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Security.Cryptography;
using System.Text;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, DataAccess = DataAccessKind.None)]

    public static SqlBinary GetHash

    (

      SqlString Algorithm,

      [SqlFacet(MaxSize = -1)] SqlBinary Plaintext

    )
    {

        if (Algorithm.IsNull || Plaintext.IsNull)

            return SqlBinary.Null;

        bool HashDefined = true;

        HashAlgorithm Hash = null;

        switch (Algorithm.Value.ToUpper())
        {
            case "SHA1":
                Hash = new SHA1Managed();
                break;

            case "SHA256":

                Hash = new SHA256Managed();

                break;



            case "SHA384":

                Hash = new SHA384Managed();

                break;



            case "SHA512":

                Hash = new SHA512Managed();

                break;



            default:

                HashDefined = false;

                break;

        }

        if (!HashDefined)

            throw new Exception("Unsupported hash algorithm - use SHA256, SHA384 or SHA512");

        byte[] HashBytes = Hash.ComputeHash(Plaintext.Value);

        // Convert result to a SqlBytes value

        return new SqlBinary(HashBytes);

    }
};

